package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.*;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.*;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.CommonUtils;
import com.sailfish.springbootdemo.utils.FileConverterUtils;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.*;

@Service
public class TechDeviceParamServiceImpl implements TechDeviceParamService {

    @Autowired
    private TechDeviceParamDao techDeviceParamDao;

    @Autowired
    private PcbaDeviceTypeDao pcbaDeviceTypeDao;

    @Autowired
    private TechDeviceParamTypeDao techDeviceParamTypeDao;

    @Autowired
    private PcbaDeviceParamDao pcbaDeviceParamDao;

    @Autowired
    private PcbaDeviceParamTypeDao pcbaDeviceParamTypeDao;

    @Autowired
    private CommonJudgeCanDeleteService commonService;

    @Autowired
    private CoreAlgorithmService coreAlgorithmService;

    @Value("${personal.config.file.file-save-url}")
    private String fileSaveUrl;

    @Value("${personal.config.amazon-s3.url}")
    private String url;
    @Value("${personal.config.amazon-s3.file-bucket}")
    private String fileBucket;
    @Value("${personal.config.env}")
    private String env;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "设备模板管理-工艺模板";

    @Override
    public List<TechDeviceParam> getAllTechDeviceParam(HttpServletRequest request, Integer pcbaDeviceTypeId, Integer techDeviceParamTypeId, String searchTechDeviceParamName) {
        List<TechDeviceParam> list = techDeviceParamDao.getAllTechDeviceParam(pcbaDeviceTypeId, techDeviceParamTypeId, searchTechDeviceParamName);
        for (TechDeviceParam techDeviceParam : list) {

            if (techDeviceParam.getTechDeviceParamPicture() != null && !"".equals(techDeviceParam.getTechDeviceParamPicture())) {
                if (env != null && env.contains("pro"))  {
                    techDeviceParam.setTechDeviceParamPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(url + "/" + fileBucket + "/" + techDeviceParam.getTechDeviceParamPicture()));
                } else {
                    if(request != null){
                        techDeviceParam.setTechDeviceParamPictureBase64(CommonUtils.base64Prefix() + CommonUtils.getImageBase64FromUrl(CommonUtils.getApiPrefixUrl(request) + "/" + techDeviceParam.getTechDeviceParamPicture()));
                    }
                }
            }

            TechDeviceParamType techDeviceParamType = techDeviceParamTypeDao.getPcbaDeviceParamTypeById(techDeviceParam.getTechDeviceParamTypeId());
            techDeviceParam.setTechDeviceParamType(techDeviceParamType);

            List<PcbaDeviceParam> pl = new ArrayList<>();
            if (techDeviceParam.getBindDeviceParamKey() != null && !"".equals(techDeviceParam.getBindDeviceParamKey())) {
                String[] arr = techDeviceParam.getBindDeviceParamKey().split(",");
                for (String s : arr) {
                    PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(s);
                    if (pcbaDeviceParamByKey != null) {
                        pcbaDeviceParamByKey.setPcbaDeviceParamType(pcbaDeviceParamTypeDao.getPcbaDeviceParamTypeById(pcbaDeviceParamByKey.getPcbaDeviceParamTypeId()));
                        pl.add(pcbaDeviceParamByKey);
                    }
                }
            }
            techDeviceParam.setBindDeviceParamList(pl);
        }
        return list;
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result analysisTechDeviceParamExcel(MultipartFile file) {
        try {
            if (file == null) {
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            List<Map<String, Object>> list = new ArrayList<>();
            // 1.得到一个输入流对象
            //FileInputStream in = FileConverterUtils.convertTo(file);
            InputStream inputStream = file.getInputStream();
            File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
            // 2.将输入流对象进行解析 得到workbook对象
            //Workbook workbook = new XSSFWorkbook(in);
            Workbook workbook = WorkbookFactory.create(f);
            // 3.workbook中有几个工作簿
            int sheetNum = workbook.getNumberOfSheets();
            System.out.println("一共有" + sheetNum + "个工作簿");
            // 3.1通过workbook 创建工作簿对象
            //Sheet sheet1 = workbook.getSheetAt(0);
            //Sheet sheet2 = workbook.getSheetAt(1);
            for (int a = 0; a < 1; a++) {
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                System.out.println("sheet" + (a + 1) + "一共有：" + allRows + "行");
                String sheetName = sheet.getSheetName();
                System.out.println("当前sheetName：" + sheetName);

                Map<String, Object> map = new HashMap<>();
                //标题行 第1行开始
                Row row = sheet.getRow(0);
                String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                String t6 = row.getCell(5) != null ? row.getCell(5).toString() : "";
                String t7 = row.getCell(6) != null ? row.getCell(6).toString() : "";
                String t8 = row.getCell(7) != null ? row.getCell(7).toString() : "";
                if (t1.contains("设备") &&
                        t2.contains("类型") &&
                        t3.contains("能力项") &&
                        t4.contains("备注") &&
                        t5.contains("宣称能力") &&
                        t6.contains("实际能力") &&
                        t7.contains("是否必填") &&
                        t8.contains("文本提示内容")
                ) {
                    // 表头符合的，循环获取每行数据
                    //List<Map<String,Object>> list2 = new ArrayList<>();
                    for (int b = 1; b < allRows; b++) {
                        Map<String, Object> map2 = new HashMap<>();
                        Row rowV = sheet.getRow(b);
                        String v1 = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                        String v2 = rowV.getCell(1) != null ? rowV.getCell(1).toString() : "";
                        String v3 = rowV.getCell(2) != null ? rowV.getCell(2).toString() : "";
                        String v4 = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                        String v5 = rowV.getCell(4) != null ? rowV.getCell(4).toString() : "";
                        String v6 = rowV.getCell(5) != null ? rowV.getCell(5).toString() : "";
                        String v7 = rowV.getCell(6) != null ? rowV.getCell(6).toString() : "";
                        String v8 = rowV.getCell(7) != null ? rowV.getCell(7).toString() : "";
                        // 第一列 设备 存在合并单元格
                        // 第二列 类型 存在合并单元格
                        // 第三列 能力项 不能为空，需要处理特殊符号
                        // 第四列 备注
                        // 第五列 宣称能力
                        // 第六列 实际能力
                        // 第七列 是否必填 为是 则必填  否则均为非必填
                        // 第八列 文本提示内容 不用管

                        String mergedCellValue1 = "";
                        String mergedCellValue2 = "";
                        // 获取合并单元格的数量
                        int mergedRegions = sheet.getNumMergedRegions();
                        for (int i = 0; i < mergedRegions; i++) {
                            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                            int firstRow = cellRangeAddress.getFirstRow();
                            int lastRow = cellRangeAddress.getLastRow();
                            int firstCol = cellRangeAddress.getFirstColumn();
                            int lastCol = cellRangeAddress.getLastColumn();
                            if (b >= firstRow && b <= lastRow && firstCol == 0 && lastCol == 0) {
                                Cell cell = sheet.getRow(firstRow).getCell(0);
                                mergedCellValue1 = cell.getStringCellValue();
                                break;
                            }
                        }
                        for (int i = 0; i < mergedRegions; i++) {
                            CellRangeAddress cellRangeAddress = sheet.getMergedRegion(i);
                            int firstRow = cellRangeAddress.getFirstRow();
                            int lastRow = cellRangeAddress.getLastRow();
                            int firstCol = cellRangeAddress.getFirstColumn();
                            int lastCol = cellRangeAddress.getLastColumn();
                            if (b >= firstRow && b <= lastRow && firstCol == 1 && lastCol == 1) {
                                Cell cell = sheet.getRow(firstRow).getCell(1);
                                mergedCellValue2 = cell.getStringCellValue();
                                break;
                            }
                        }
                        //System.out.println("mergedCellValue1===" + mergedCellValue1);
                        //System.out.println("mergedCellValue2===" + mergedCellValue2);
                        map2.put("pcbaDeviceTypeName", (v1 != null && !"".equals(v1)) ? v1 : mergedCellValue1);
                        map2.put("techDeviceParamType", (v2 != null && !"".equals(v2)) ? v2 : mergedCellValue2);
                        map2.put("techDeviceParamName", v3);
                        map2.put("notes", v4);
                        map2.put("techDeviceParamFillType", v5);
                        map2.put("actualEqualDeclare", v6);
                        map2.put("isRequired", "是".equals(v7) ? 1 : 2);
                        map2.put("techDeviceParamPlaceholder", v8);
                        list.add(map2);
                    }
                    //map.put("pcbaDeviceParamList", list2);
                } else {
                    return ResultUtil.error(500, "模板错误", "Error Template", null);
                }
                //list.add(map);
            }
            //return ResultUtil.success(list);
            // 得到list 然后做处理
            int importNum = 0;
            List<TechDeviceParam> addList = new ArrayList<>();
            String userId = UserHeaderHolder.getUserId();
            Date d = new Date();
            for (Map<String, Object> h : list) {
                String isRequired = h.get("isRequired") != null ? h.get("isRequired").toString() : "2";
                String notes = h.get("notes") != null ? h.get("notes").toString() : "";
                String techDeviceParamFillType = h.get("techDeviceParamFillType") != null ? h.get("techDeviceParamFillType").toString() : "";
                String techDeviceParamName = h.get("techDeviceParamName") != null ? h.get("techDeviceParamName").toString() : "";
                String techDeviceParamPlaceholder = h.get("techDeviceParamPlaceholder") != null ? h.get("techDeviceParamPlaceholder").toString() : "";
                String techDeviceParamType = h.get("techDeviceParamType") != null ? h.get("techDeviceParamType").toString() : "";
                String pcbaDeviceTypeName = h.get("pcbaDeviceTypeName") != null ? h.get("pcbaDeviceTypeName").toString() : "";
                String actualEqualDeclare = h.get("actualEqualDeclare") != null ? h.get("actualEqualDeclare").toString() : "";
                // 判断设备类型
                PcbaDeviceType pcbaDevice = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeName);
                if (pcbaDevice != null) {
                    int pcbaDeviceTypeId = pcbaDevice.getPcbaDeviceTypeId();
                    if (techDeviceParamType != null && !"".equals(techDeviceParamType)) {
                        // 判断能力项分类
                        TechDeviceParamType techDeviceParamType1 = techDeviceParamTypeDao.getByTechDeviceTypeIdAndName(pcbaDeviceTypeId, techDeviceParamType);
                        if (techDeviceParamType1 != null) {
                            int techDeviceParamTypeId = techDeviceParamType1.getTechDeviceParamTypeId();
                            // 判断能力项
                            TechDeviceParam techDeviceParam = techDeviceParamDao.getByNameAndTechDeviceParamTypeId(techDeviceParamTypeId, techDeviceParamName);
                            if (techDeviceParam == null) {
                                if (techDeviceParamFillType != null && !"".equals(techDeviceParamFillType)) {
                                    // insert
                                    TechDeviceParam addTechDeviceParam = new TechDeviceParam();
                                    addTechDeviceParam.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                                    addTechDeviceParam.setTechDeviceParamNameCn(techDeviceParamName);
                                    addTechDeviceParam.setTechDeviceParamNameEn(techDeviceParamName);
                                    addTechDeviceParam.setTechDeviceParamKey("bulk_" + System.currentTimeMillis());
                                    addTechDeviceParam.setCreateTime(d);
                                    addTechDeviceParam.setSort(100);
                                    addTechDeviceParam.setStatus(1);
                                    addTechDeviceParam.setIsRequired(Integer.parseInt(isRequired));
                                    addTechDeviceParam.setTechDeviceParamTypeId(techDeviceParamTypeId);
                                    addTechDeviceParam.setTechDeviceParamPlaceholder(techDeviceParamPlaceholder);
                                    addTechDeviceParam.setActualEqualDeclare("等于宣称能力".equals(actualEqualDeclare) ? 1 : 2);
                                    addTechDeviceParam.setNotes(notes);
                                    //1：普通文本
                                    //2.下拉选择
                                    //3：文件上传
                                    //4：来源基线
                                    //5：取多个基线最小值
                                    //11：数值类型[整数]
                                    //12：数值类型[小数]
                                    int fillType = 1;
                                    String fillOptions = "";
                                    if ("普通文本".equals(techDeviceParamFillType)) {
                                        fillType = 1;
                                    } else if ("整数".equals(techDeviceParamFillType)) {
                                        fillType = 11;
                                    } else if ("小数".equals(techDeviceParamFillType)) {
                                        fillType = 12;
                                    } else if (techDeviceParamFillType.contains("下拉选择")) {
                                        fillType = 2;
                                        fillOptions = techDeviceParamFillType.replace("下拉选择", "").replaceAll("（", "").replaceAll("\\(", "").replaceAll("）", "").replaceAll("\\)", "").replaceAll("，", ",");
                                    }
                                    addTechDeviceParam.setTechDeviceParamFillType(fillType);
                                    addTechDeviceParam.setTechDeviceParamOptions(fillOptions);
                                    techDeviceParamDao.addTechDeviceParam(addTechDeviceParam);
                                    importNum++;
                                    addList.add(addTechDeviceParam);
                                }
                            }
                        }
                    }
                }
            }

            if (addList.size() > 0) {
                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, d, null, JSONObject.toJSONString(addList)));
            }

            Map<String, Object> mm = new HashMap<>();
            mm.put("list", list);
            mm.put("importNum", importNum);
            return ResultUtil.success(mm);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
        /* try{
            if(file == null){
                return ResultUtil.error(500, "缺少参数file", "Miss Param file", null);
            }
            List<Map<String, Object>> list = new ArrayList<>();
            // 1.得到一个输入流对象
            //FileInputStream in = FileConverterUtils.convertTo(file);
            InputStream inputStream = file.getInputStream();
            File f = FileConverterUtils.getTempFileFromInputStream(inputStream);
            // 2.将输入流对象进行解析 得到workbook对象
            //Workbook workbook = new XSSFWorkbook(in);
            Workbook workbook = WorkbookFactory.create(f);
            // 3.workbook中有几个工作簿
            int sheetNum = workbook.getNumberOfSheets();
            System.out.println("一共有" + sheetNum + "个工作簿");
            // 3.1通过workbook 创建工作簿对象
            //Sheet sheet1 = workbook.getSheetAt(0);
            //Sheet sheet2 = workbook.getSheetAt(1);
            for(int a = 0;a<sheetNum;a++){
                Sheet sheet = workbook.getSheetAt(a);
                int allRows = sheet.getLastRowNum() + 1;
                System.out.println("sheet" + (a+1) + "一共有：" + allRows + "行");
                String sheetName = sheet.getSheetName();
                System.out.println("当前sheetName：" + sheetName);

                Map<String, Object> map = new HashMap<>();
                if(sheetName != null &&  !"".equals(sheetName)){
                    //判断sheetName在不在设备列表里面
                    List<PcbaDeviceType> pcbaDeviceList = pcbaDeviceTypeDao.getAllPcbaDeviceType();
                    List<String> pcbaDeviceNameList = new ArrayList<>();
                    for (PcbaDeviceType p : pcbaDeviceList) {
                        pcbaDeviceNameList.add(p.getPcbaDeviceTypeNameCn());
                    }
                    if(pcbaDeviceNameList.contains(sheetName)){
                        map.put("pcbaDeviceTypeNameCn", sheetName);
                        //标题行
                        Row row = sheet.getRow(0);
                        String t1 = row.getCell(0) != null ? row.getCell(0).toString() : "";
                        String t2 = row.getCell(1) != null ? row.getCell(1).toString() : "";
                        String t3 = row.getCell(2) != null ? row.getCell(2).toString() : "";
                        String t4 = row.getCell(3) != null ? row.getCell(3).toString() : "";
                        String t5 = row.getCell(4) != null ? row.getCell(4).toString() : "";
                        System.out.println(t1);
                        System.out.println(t2);
                        System.out.println(t3);
                        System.out.println(t4);
                        System.out.println(t5);
                        if(t1.contains("参数名中文") && t2.contains("参数名英文") && t3.contains("参数默认值") && t4.contains("参数唯一key") && t5.contains("参数是否必填")){
                            // 表头符合的，循环获取每行数据
                            List<Map<String,Object>> list2 = new ArrayList<>();
                            for(int b = 1; b<allRows; b++){
                                Map<String,Object> map2 = new HashMap<>();
                                Row rowV = sheet.getRow(b);
                                String v1 = rowV.getCell(0) != null ? rowV.getCell(0).toString() : "";
                                String v2 = rowV.getCell(1) != null ? rowV.getCell(1).toString() : "";
                                String v3 = rowV.getCell(2) != null ? rowV.getCell(2).toString() : "";
                                String v4 = rowV.getCell(3) != null ? rowV.getCell(3).toString() : "";
                                String v5 = rowV.getCell(4) != null ? rowV.getCell(4).toString() : "";
                                System.out.println(v1);
                                System.out.println(v2);
                                System.out.println(v3);
                                System.out.println(v4);
                                System.out.println(v5);
                                // 第一列，第二列，第四列不能为空，否则不处理
                                if(!"".equals(v1) && !"".equals(v2) && !"".equals(v4)){
                                    map2.put("pcbaDeviceParamNameCn", v1);
                                    map2.put("pcbaDeviceParamNameEn", v2);
                                    map2.put("pcbaDeviceParamDefault", v3);
                                    map2.put("pcbaDeviceParamKey", v4);
                                    map2.put("isRequired", "是".equals(v5) ? 1 : 2);
                                    list2.add(map2);
                                }
                            }
                            map.put("pcbaDeviceParamList", list2);
                        }
                    }
                }
                list.add(map);
            }

            // 得到list 然后做处理
            int importNum = 0;
            for (Map<String,Object> h : list) {
                String pcbaDeviceTypeNameCn = h.get("pcbaDeviceTypeNameCn") != null ? h.get("pcbaDeviceTypeNameCn").toString() : "";
                PcbaDeviceType pcbaDevice = pcbaDeviceTypeDao.getPcbaDeviceTypeByNameCn(pcbaDeviceTypeNameCn);
                if(pcbaDevice != null){
                    Integer pcbaDeviceTypeId = pcbaDevice.getPcbaDeviceTypeId();
                    Object oList = h.get("pcbaDeviceParamList");
                    List<Map<String, Object>> mapList = (ArrayList)oList;
                    for (Map<String,Object> m: mapList) {
                        String pcbaDeviceParamNameCn = m.get("pcbaDeviceParamNameCn") != null ? m.get("pcbaDeviceParamNameCn").toString() : "";
                        String pcbaDeviceParamNameEn = m.get("pcbaDeviceParamNameEn") != null ? m.get("pcbaDeviceParamNameEn").toString() : "";
                        String pcbaDeviceParamDefault = m.get("pcbaDeviceParamDefault") != null ? m.get("pcbaDeviceParamDefault").toString() : "";
                        String pcbaDeviceParamKey = m.get("pcbaDeviceParamKey") != null ? m.get("pcbaDeviceParamKey").toString() : "";
                        String isRequired = m.get("isRequired") != null ? m.get("isRequired").toString() : "2";
                        // 判断是否已有
                        PcbaDeviceParam searchPcbaDeviceParam = new PcbaDeviceParam();
                        searchPcbaDeviceParam.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                        searchPcbaDeviceParam.setPcbaDeviceParamNameCn(pcbaDeviceParamNameCn);
                        searchPcbaDeviceParam.setPcbaDeviceParamNameEn(pcbaDeviceParamNameEn);
                        searchPcbaDeviceParam.setPcbaDeviceParamDefault(pcbaDeviceParamDefault);
                        searchPcbaDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                        PcbaDeviceParam byPcbaDeviceParam = techDeviceParamDao.getByTechDeviceParam(searchPcbaDeviceParam);
                        if(byPcbaDeviceParam == null){
                            // insert
                            PcbaDeviceParam addPcbaDeviceParam = new PcbaDeviceParam();
                            addPcbaDeviceParam.setPcbaDeviceTypeId(pcbaDeviceTypeId);
                            addPcbaDeviceParam.setPcbaDeviceParamNameCn(pcbaDeviceParamNameCn);
                            addPcbaDeviceParam.setPcbaDeviceParamNameEn(pcbaDeviceParamNameEn);
                            addPcbaDeviceParam.setPcbaDeviceParamDefault(pcbaDeviceParamDefault);
                            addPcbaDeviceParam.setPcbaDeviceParamKey(pcbaDeviceParamKey);
                            addPcbaDeviceParam.setCreateTime(new Date());
                            addPcbaDeviceParam.setSort(100);
                            addPcbaDeviceParam.setStatus(1);
                            addPcbaDeviceParam.setIsRequired(Integer.parseInt(isRequired));
                            techDeviceParamDao.addPcbaTechParam(addPcbaDeviceParam);
                            importNum ++;
                        }
                    }
                }
            }
            Map<String,Object> mm = new HashMap<>();
            mm.put("list", list);
            mm.put("importNum", importNum);
            return ResultUtil.success(mm);
        }catch (Exception e){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }*/
    }

    @Override
    public Result deleteById(Integer techDeviceParamId) {
        try {
            if (techDeviceParamId == null || "".equals(techDeviceParamId.toString())) {
                return ResultUtil.error(500, "缺少参数techDeviceParamId", "Miss Param techDeviceParamId", null);
            }
            TechDeviceParam techDeviceParamById = techDeviceParamDao.getTechDeviceParamById(techDeviceParamId);
            String judgeKey = techDeviceParamById.getTechDeviceParamKey();
            Map<String, Integer> stringIntegerMap = commonService.judgeCanDeleteTechDeviceParam(judgeKey);
            if (stringIntegerMap.get("relatedRoadmapParamNum") > 0) {
                return ResultUtil.error(500,
                        "禁止删除，当前项" + stringIntegerMap.get("relatedRoadmapParamNum") + "处应用于roadmap能力项规则",
                        "Forbidden Delete", null);
            }

            if (techDeviceParamById.getIsRelatedPcba() != null && techDeviceParamById.getIsRelatedPcba() == 1) {
                return ResultUtil.error(500, "参与pcba能力匹配，禁止删除", "Forbidden Delete", null);
            }

            String userId = UserHeaderHolder.getUserId();

            Integer i = techDeviceParamDao.deleteById(techDeviceParamId);
            if (i > 0) {

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(techDeviceParamById), null));
                //coreAlgorithmService.cascadeChangeAllParams("1_2", techDeviceParamById.getPcbaDeviceTypeId(), null);
                return ResultUtil.success(null);
            }
            return ResultUtil.error(500, "操作失败", "Operate Fail", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Boolean addPcbaDeviceParam(TechDeviceParam techDeviceParam) {
        techDeviceParam.setCreateTime(new Date());
        //coreAlgorithmService.cascadeChangeAllParams("1_2", techDeviceParam.getPcbaDeviceTypeId(), null);
        return techDeviceParamDao.addTechDeviceParam(techDeviceParam) > 0;
    }

    @Override
    public Boolean updatePcbaDeviceParam(TechDeviceParam techDeviceParam) {
        techDeviceParam.setUpdateTime(new Date());
        return techDeviceParamDao.updateTechDeviceParam(techDeviceParam) > 0;
    }

    @Override
    public Result addOrUpdateTechDeviceParam(TechDeviceParam techDeviceParam, String mode) {
        try {
            if (techDeviceParam == null) {
                return ResultUtil.error(500, "缺少参数techDeviceParam", "Miss Param techDeviceParam", null);
            }
            if (mode == null || "".equals(mode)) {
                return ResultUtil.error(500, "缺少参数mode", "Miss Param mode", null);
            }
            if (!("update".equals(mode) || "add".equals(mode))) {
                return ResultUtil.error(500, "mode 参数错误", "mode Param Error", null);
            }

            String userId = UserHeaderHolder.getUserId();

            if ("update".equals(mode)) {
                if (techDeviceParam.getTechDeviceParamId() == null || "".equals(techDeviceParam.getTechDeviceParamId().toString())) {
                    return ResultUtil.error(500, "缺少参数techDeviceParamId", "Miss Param techDeviceParamId", null);
                }

                List<TechDeviceParam> techDeviceParamList = techDeviceParamDao.judgeUniqueTechDeviceParam(techDeviceParam.getPcbaDeviceTypeId(), techDeviceParam.getTechDeviceParamTypeId(), techDeviceParam.getTechDeviceParamId(), techDeviceParam.getTechDeviceParamNameCn());
                if (techDeviceParamList.size() > 0) {
                    return ResultUtil.error(500, "修改失败，存在相同名字", "Operate Fail", null);
                }

                TechDeviceParam oldTechDeviceParam = techDeviceParamDao.getTechDeviceParamById(techDeviceParam.getTechDeviceParamId());

                techDeviceParam.setUpdateTime(new Date());
                // 处理 类型等于 4或者5的情况
                if ("4".equals(techDeviceParam.getTechDeviceParamFillType().toString())) {
                    PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(techDeviceParam.getBindDeviceParamKey());
                    if (pcbaDeviceParamByKey != null) {
                        techDeviceParam.setSupplyTechDeviceParamFillType(pcbaDeviceParamByKey.getPcbaDeviceParamFillType());
                    }
                }
                if ("5".equals(techDeviceParam.getTechDeviceParamFillType().toString())) {
                    String keys = techDeviceParam.getBindDeviceParamKey();
                    if (keys != null && !"".equals(keys)) {
                        String[] arr = keys.split(",");
                        PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(arr[0]);
                        if (pcbaDeviceParamByKey != null) {
                            techDeviceParam.setSupplyTechDeviceParamFillType(pcbaDeviceParamByKey.getPcbaDeviceParamFillType());
                        }
                    }
                }
                int a = techDeviceParamDao.updateTechDeviceParam(techDeviceParam);
                if (a > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldTechDeviceParam), JSONObject.toJSONString(techDeviceParam)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            } else {

                TechDeviceParam techDeviceParamByName = techDeviceParamDao.getTechDeviceParamByName(techDeviceParam.getPcbaDeviceTypeId(), techDeviceParam.getTechDeviceParamTypeId(), techDeviceParam.getTechDeviceParamNameCn());
                if (techDeviceParamByName != null) {
                    return ResultUtil.error(500, "该项已存在", "Already Exist", null);
                }

                techDeviceParam.setCreateTime(new Date());
                // 处理 类型等于 4或者5的情况
                if ("4".equals(techDeviceParam.getTechDeviceParamFillType().toString())) {
                    PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(techDeviceParam.getBindDeviceParamKey());
                    if (pcbaDeviceParamByKey != null) {
                        techDeviceParam.setSupplyTechDeviceParamFillType(pcbaDeviceParamByKey.getPcbaDeviceParamFillType());
                    }
                }
                if ("5".equals(techDeviceParam.getTechDeviceParamFillType().toString())) {
                    String keys = techDeviceParam.getBindDeviceParamKey();
                    if (keys != null && !"".equals(keys)) {
                        String[] arr = keys.split(",");
                        PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(arr[0]);
                        if (pcbaDeviceParamByKey != null) {
                            techDeviceParam.setSupplyTechDeviceParamFillType(pcbaDeviceParamByKey.getPcbaDeviceParamFillType());
                        }
                    }
                }
                int a = techDeviceParamDao.addTechDeviceParam(techDeviceParam);
                if (a > 0) {

                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(techDeviceParam)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result changeActualEqualDeclare(Integer techDeviceParamId) {
        try {
            if (techDeviceParamId == null || "".equals(techDeviceParamId.toString())) {
                return ResultUtil.error(500, "缺少参数techDeviceParamId", "Miss Param techDeviceParamId", null);
            }

            String userId = UserHeaderHolder.getUserId();

            TechDeviceParam techDeviceParamById = techDeviceParamDao.getTechDeviceParamById(techDeviceParamId);
            if (techDeviceParamById != null) {
                Integer actualEqualDeclare1 = techDeviceParamById.getActualEqualDeclare();
                Integer newActualEqualDeclare = null;
                if (actualEqualDeclare1 == null || !"1".equals(actualEqualDeclare1.toString())) {
                    newActualEqualDeclare = 1;
                }
                Integer count = techDeviceParamDao.changeActualEqualDeclare(techDeviceParamId, newActualEqualDeclare);
                if (count > 0) {

                    TechDeviceParam newTechDeviceParam = techDeviceParamById;
                    newTechDeviceParam.setActualEqualDeclare(newActualEqualDeclare);
                    // 操作日志
                    operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(techDeviceParamById), JSONObject.toJSONString(newTechDeviceParam)));

                    return ResultUtil.success(null);
                }
                return ResultUtil.error(500, "操作失败", "Operate Fail", null);
            }
            return ResultUtil.error(500, "未找到TechDeviceParam", "Not Found TechDeviceParam", null);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result exportTechDeviceParamExcel() {
        try {
            String excelName = "设备工艺能力参数模板";

            List<PcbaDeviceType> list = pcbaDeviceTypeDao.getAllPcbaDeviceType(null, 2);

            // 创建工作簿对象
            Workbook workbook = new XSSFWorkbook();
            // 创建工作表对象
            Sheet sheet = workbook.createSheet(CommonUtils.handleSheetName(excelName));
            // 创建行和单元格对象
            Row row = sheet.createRow(0);
            Cell cell;
            /*CellStyle bigTitleContextCellStyle = workbook.createCellStyle();
            Font bigTitleFont = workbook.createFont();
            bigTitleFont.setBold(true);
            bigTitleFont.setFontHeightInPoints((short)20);
            bigTitleContextCellStyle.setFont(bigTitleFont);
            bigTitleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
            bigTitleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 第一行大标题【设备基线能力参数反馈表】
            Cell cell = row.createCell(0);
            cell.setCellValue("设备基线能力参数反馈表");
            cell.setCellStyle(bigTitleContextCellStyle);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 6));
            // 第二行 【注：模板内容不涉及，则填写NA】
            row = sheet.createRow(1);
            cell = row.createCell(0);
            cell.setCellValue("注：模板内容不涉及，则填写NA");
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 6));
*/

            CellStyle bodyContextCellStyle = workbook.createCellStyle();
            DataFormat format = workbook.createDataFormat();
            bodyContextCellStyle.setDataFormat(format.getFormat("@"));
            bodyContextCellStyle.setBorderBottom(BorderStyle.THIN);
            bodyContextCellStyle.setBorderLeft(BorderStyle.THIN);
            bodyContextCellStyle.setBorderRight(BorderStyle.THIN);
            bodyContextCellStyle.setBorderTop(BorderStyle.THIN);
            bodyContextCellStyle.setAlignment(HorizontalAlignment.LEFT);
            bodyContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

            CellStyle titleContextCellStyle = workbook.createCellStyle();
            titleContextCellStyle.setBorderBottom(BorderStyle.THIN);
            titleContextCellStyle.setBorderLeft(BorderStyle.THIN);
            titleContextCellStyle.setBorderRight(BorderStyle.THIN);
            titleContextCellStyle.setBorderTop(BorderStyle.THIN);
            titleContextCellStyle.setAlignment(HorizontalAlignment.CENTER);
            titleContextCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
            // 设置背景色为红色
            titleContextCellStyle.setFillForegroundColor(IndexedColors.BLUE.getIndex());
            // 创建字体对象
            Font titleFont = workbook.createFont();
            // 设置字体颜色为蓝色
            titleFont.setColor(IndexedColors.WHITE.getIndex());
            titleFont.setBold(true);
            titleContextCellStyle.setFont(titleFont);
            // 设置填充类型为填充实体背景
            titleContextCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            List<Map<String, Object>> titleList = new ArrayList<>();

            Map<String, Object> map = new HashMap<>();
            map = new HashMap<>();
            map.put("title", "设备");
            map.put("width", 6000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "类型");
            map.put("width", 6000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "能力项");
            map.put("width", 15000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "备注");
            map.put("width", 6000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "宣称能力");
            map.put("width", 15000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "实际能力");
            map.put("width", 15000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "是否必填");
            map.put("width", 4000);
            titleList.add(map);
            map = new HashMap<>();
            map.put("title", "文本提示内容");
            map.put("width", 15000);
            titleList.add(map);
            row = sheet.createRow(0);
            for (int a = 0; a < titleList.size(); a++) {
                sheet.setColumnWidth(a, Integer.parseInt(titleList.get(a).get("width").toString()));
                sheet.setDefaultRowHeight((short) 450);
                cell = row.createCell(a);
                // 向单元格中写入数据
                cell.setCellValue(titleList.get(a).get("title").toString());
                cell.setCellStyle(titleContextCellStyle);
            }

            int index = 0; // 序号
            int beginIndex1 = 1; //用于计算合并单元格 【设备】一列，从第四行开始
            int beginIndex2 = 1; //用于计算合并单元格 【项目大类】一列，从第四行开始

            List<TechDeviceParamType> techDeviceParamTypeList = new ArrayList<>();
            // 渲染数据
            for (int b = 0; b < list.size(); b++) {
                techDeviceParamTypeList = techDeviceParamTypeDao.getAllTechDeviceParamTypeByDeviceType(list.get(b).getPcbaDeviceTypeId(), null);

                if (techDeviceParamTypeList != null && techDeviceParamTypeList.size() > 0) {
                    for (int c = 0; c < techDeviceParamTypeList.size(); c++) {
                        List<TechDeviceParam> techDeviceParamList = techDeviceParamDao.getAllTechDeviceParam(null, techDeviceParamTypeList.get(c).getTechDeviceParamTypeId(), null);
                        if (techDeviceParamList != null && techDeviceParamList.size() > 0) {
                            for (int d = 0; d < techDeviceParamList.size(); d++) {

                                if (techDeviceParamList.get(d).getBindDeviceParamKey() != null && !"".equals(techDeviceParamList.get(d).getBindDeviceParamKey())) {
                                    String[] arr = techDeviceParamList.get(d).getBindDeviceParamKey().split(",");
                                    List<PcbaDeviceParam> l = new ArrayList<>();
                                    for (String s : arr) {
                                        PcbaDeviceParam pcbaDeviceParamByKey = pcbaDeviceParamDao.getPcbaDeviceParamByKey(s);
                                        l.add(pcbaDeviceParamByKey);
                                    }
                                    techDeviceParamList.get(d).setBindDeviceParamList(l);
                                }

                                index++;
                                Row row_ = sheet.createRow(index);

                                Cell cell_;

                                // 设备
                                cell_ = row_.createCell(0);
                                cell_.setCellValue(list.get(b).getPcbaDeviceTypeNameCn());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 类型
                                cell_ = row_.createCell(1);
                                cell_.setCellValue(techDeviceParamTypeList.get(c).getTechDeviceParamTypeName());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 能力项
                                cell_ = row_.createCell(2);
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamNameCn());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 备注
                                cell_ = row_.createCell(3);
                                cell_.setCellValue(techDeviceParamList.get(d).getNotes());
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 宣称能力
                                /*1：普通文本
                                    2.下拉选择
                                    3：文件上传
                                    4：来源基线
                                    5：取多个基线最小值
                                    10：数值类型[整数]
                                    11：数值类型[小数]*/
                                cell_ = row_.createCell(4);
                                String bindStr = "";
                                List<PcbaDeviceParam> bindList = techDeviceParamList.get(d).getBindDeviceParamList();
                                if (bindList != null && bindList.size() > 0) {
                                    for (PcbaDeviceParam pcbaDeviceParam : bindList) {
                                        if (pcbaDeviceParam != null) {
                                            bindStr = bindStr + pcbaDeviceParam.getPcbaDeviceParamNameCn() + ",";
                                        }
                                    }
                                    if (bindStr.length() > 0) {
                                        bindStr = bindStr.substring(0, bindStr.length() - 1);
                                    }
                                }
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamFillType() == 1 ? "普通文本" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 2 ? "下拉选择" + "(" + techDeviceParamList.get(d).getTechDeviceParamOptions() + ")" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 3 ? "文件上传" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 11 ? "整数" : (techDeviceParamList.get(d).getTechDeviceParamFillType() == 12 ? "小数" : ((techDeviceParamList.get(d).getTechDeviceParamFillType() == 4 ? "来源基线(" + bindStr + ")" : ((techDeviceParamList.get(d).getTechDeviceParamFillType() == 5 ? "取多个基线最小值(" + bindStr + ")" : "")))))))));
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 实际能力
                                cell_ = row_.createCell(5);
                                cell_.setCellValue((techDeviceParamList.get(d).getActualEqualDeclare() != null && techDeviceParamList.get(d).getActualEqualDeclare() == 1) ? "等于宣称能力" : "");
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 是否必填
                                cell_ = row_.createCell(6);
                                cell_.setCellValue(techDeviceParamList.get(d).getIsRequired() == 1 ? "是" : "否");
                                cell_.setCellStyle(bodyContextCellStyle);

                                // 文本提示内容
                                cell_ = row_.createCell(7);
                                cell_.setCellValue(techDeviceParamList.get(d).getTechDeviceParamPlaceholder());
                                cell_.setCellStyle(bodyContextCellStyle);
                            }
                            // 合并第三列 【项目大类】
                            if (techDeviceParamList.size() > 1) {
                                if (index > beginIndex2) {
                                    sheet.addMergedRegion(new CellRangeAddress(beginIndex2, index, 1, 1));
                                    beginIndex2 = index + 1;
                                }
                            } else {
                                beginIndex2 = index + 1;
                            }
                        }
                    }
                    // 合并第二列 【设备】
                    //System.out.println("beginRow===" + beginIndex1);
                    //System.out.println("lastRow===" + (index + 2));
                    //if(techDeviceParamTypeList.size() > 1){
                    if (index > beginIndex1) {
                        sheet.addMergedRegion(new CellRangeAddress(beginIndex1, index, 0, 0));
                        beginIndex1 = index + 1;
                    }
                    /*}else{
                        beginIndex1 = index + 1;
                    }*/
                }
            }

            String fileName = excelName + CommonUtils.getTimestamp() + ".xlsx";
            String pathPrefix = fileSaveUrl + "exportExcels\\";
            File folder = new File(pathPrefix);
            if (!folder.isDirectory()) {
                folder.mkdirs();
            }
            String filePath = pathPrefix + fileName;
            // 导出Excel文件
            FileOutputStream outputStream = new FileOutputStream(filePath);
            workbook.write(outputStream);
            workbook.close();
            outputStream.close();

            byte[] data = null;
            InputStream in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
            java.util.Base64.Encoder encoder = java.util.Base64.getEncoder();
            String base64 = encoder.encodeToString(data);

            Map<String, Object> resMap = new HashMap<>();
            resMap.put("base64", base64);
            resMap.put("fileName", fileName);
            resMap.put("techDeviceParamTypeList", techDeviceParamTypeList);
            return ResultUtil.success(resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Result getTechDeviceParamByKey(String techDeviceParamKey) {
        try {
            if (techDeviceParamKey == null || "".equals(techDeviceParamKey)) {
                return ResultUtil.error(500, "缺少参数techDeviceParamKey", "Miss Param techDeviceParamKey", null);
            }
            return ResultUtil.success(techDeviceParamDao.getTechDeviceParamByKey(techDeviceParamKey));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }
}
